﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Eco.AutoContainers;
using Eco.ObjectRepresentation;
using CommandLists.Model;
using Eco.Handles;
using Eco.Services;
using Descriptions_DomainModel.Model;
using System.IO;
using CommonClasses.Utility;

namespace CommandEditor
{
    /// <summary>
    /// Форма-редактор для класса Command
    /// </summary>
    public partial class CommandEditForm : Form
    {
        IUndoService undo;        
        bool result = false;

        private CommandEditForm(EcoSpace space, Command element)
        {
            InitializeComponent();            
            CurrentElement.EcoSpace = space;
            CurrentElement.SetElementValue<Command>(element);            
            undo = CurrentElement.EcoSpace.GetEcoService<IUndoService>();
            undo.StartTransaction();
        }
        /// <summary>
        /// Открыть форму редактирования для данного объекта
        /// </summary>
        /// <param name="space">ECO-пространство</param>
        /// <param name="element">Редактируемый элемент</param>
        public static void Edit(EcoSpace space, Command element)
        {
            if (element == null) return;
            if (space == null) return;
            var form = new CommandEditForm(space, element);
            form.ShowDialog();
        }

        private void OkButton_Click(object sender, EventArgs e)
        {
            result = true;
            this.Close();
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ChooseFuncButton_Click(object sender, EventArgs e)
        {
            //запрашиваем у пользователя функцию
            var function = ChooseOneForm<Function>
                .Choose("Выберите функцию",
                    CurrentElement.EcoSpace.GetEcoService<IOclService>()
                    .Evaluate("Function.allInstances").GetAsIList<Function>());

            //Если ничего не выбрано, то выходим
            if (function == null) return;

            //получаем её имя
            (CurrentElement.Element.AsObject as Command).FunctionName = function.Name;

            //получаем её параметры
            (CurrentElement.Element.AsObject as Command).Parameters.Clear();

            foreach (var param in function.Parameters)            
                (CurrentElement.Element.AsObject as Command).Parameters.Add(
                    new CommandParameter(param));            
        }

        private void CommandEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (result)
                undo.CommitTransaction();
            else
                undo.RollbackTransaction();
        }

        private void ChooseImageButton_Click(object sender, EventArgs e)
        {
            openImageDialog.FileName = (CurrentElement.Element.AsObject as Command).ImagePath;
            openImageDialog.ShowDialog();
        }

        private void openImageDialog_FileOk(object sender, CancelEventArgs e)
        {
            (CurrentElement.Element.AsObject as Command).ImagePath =
                PathUtility.MakePathLocal(openImageDialog.FileName, Locality.ExeFile);
        }

        private void ParamsDGV_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
            MessageBox.Show("Некорректное значение параметра");
        }
    }
}
